<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="file" id="fielinput"/>
    <img id="txshow" style="width:100px;height:100px;"/>
    <button onclick="funDownload()">下载图片</button>
    <script>
        var input = document.getElementById("fielinput");
        var txshow = document.getElementById("txshow");
        input.addEventListener('change', readFile, false);

        function readFile() {
            var file = this.files[0];
            var reader = new FileReader(); // 返回一个新的FileReader函数
            reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file);
            reader.onload = function (e) {
                console.log(reader.result);
                // txshow.src = this.result;
                transformArrayBufferToBase64(reader.result)
            }
        }

        function transformArrayBufferToBase64 (buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            for (var len = bytes.byteLength, i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            console.log(binary)
            console.log(window.btoa(binary))
            console.log(txshow)
            txshow.src = 'data:image/png;base64,'+ window.btoa(binary);
            txshow.src = '';
            return window.btoa(binary);
        }
        function funDownload(domImg, fileName) {
          // 创建隐藏的可下载链接
          let eleLink = document.createElement('a');
          eleLink.download = filename;
          eleLink.style.display = 'none';
          // 图片转base64地址
          let canvas = document.createElement('canvas');
          let context = canvas.getContext('2d');
          let width = domImg.naturalWidth;
          let height = domImg.naturalHeight;
          context.drawImage(domImg, 0, 0);
          // 如果是PNG图片，则canvas.toDataURL('image/png')
          eleLink.href = canvas.toDataURL('image/jpeg');
          // 触发点击
          document.body.appendChild(eleLink);
          eleLink.click();
          // 然后移除
          document.body.removeChild(eleLink);
        };
    </script>
</body>
</html>